#include "gameui.h"
#include "ui_gameui.h"
#include <Qrect>
#include <QPainter>
#include <QTimer>
#include <QKeyEvent>
#include <cstdlib>
#include <ctime>
#include <QVector>
#include <queue>
#include <QPushButton>
#include <QDebug>
#include <QDateTime>
#include <QThread>
#include <QTextStream>
#include "usualbutton.h"

GameUI::GameUI(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GameUI),
    blsRun(false)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);//调用close时就调用析构，释放空间
    setFixedSize(1900,1000);
    setWindowTitle("CTYYPE");
    //    设置图标
   setWindowIcon(QIcon(":/image/enemy1.png"));
    ui->pushButton->hide();
    ui->gameover->hide();
    QFont font("Times New Roman",10,75);
    ui->lcdNumber->setDigitCount(3);
    ui->lcdNumber->setSegmentStyle(QLCDNumber::Flat);
    ui->gameover->setStyleSheet("QLabel {color:#595959;}");
    ui->pushButton->setStyleSheet("QPushButton:hover{font-family:'幼圆'; font:30px; color:#FBF8F3; background-color: #595959; border-width:3px; border-color:#FBF8F3; border-radius: 20px;}"
                        "QPushButton{font-family:'幼圆'; font:30px; color:#595959; background-color: #FBF8F3; border-width:3px; border-color:#595959; border-radius: 20px;}");
    ui->UINput->setStyleSheet("QLabel {background-color:#FBF8F3; border:3px solid #595959; color:#F5992D;}");  //设置样式表

    //设置按钮边框阴影
    QGraphicsDropShadowEffect *shadow_effect3 = new QGraphicsDropShadowEffect(this);
    shadow_effect3->setOffset(5, 5);
    shadow_effect3->setColor(QColor(43, 43, 43));
    shadow_effect3->setBlurRadius(8);
    ui->pushButton->setGraphicsEffect(shadow_effect3);

    connect(ui->pushButton,&QPushButton::clicked,[=](){

        resultP=new ResultUI();
//        qDebug()<<wrongCount;
//        qDebug()<<score;
//        qDebug()<<wrongCount[2];
        resultP->setPp(wrongCount, score, wrongWords);
        resultP->show();
        this->close();

    });
}

void GameUI::setParameter(double pct, int gt, int mw, int npc, QString fm)
{
    planeCount_time=pct;
    gameTime=gt;
    Max_wrong=mw;
    newplaneTime=npc;
    filename=fm;
    getWords();
}

void GameUI::getWords()
{
    //用IODevice方式打开文本文件
    QFile file(filename);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QString line;
        QString tempp="";
        QTextStream in(&file);  //用文件构造流
        line = in.readLine();//读取一行放到字符串里
        while(!line.isNull())//字符串有内容
        {
            tempp+=line+" ";
            line = in.readLine();//循环读取下行
        }
        words=tempp.split(" ");
        words.removeDuplicates ();// 该方法去除调用其的QStringList中的重复项目，注意不需要对QStringList中的元素进行排序，去除后仍旧保持原来的顺序，函数返回remove掉的重复条目的数目

    }
    file.close();
}

GameUI::~GameUI()
{
    delete timeP;
    delete timer;
    delete ui;
}


void GameUI::paintEvent(QPaintEvent *event)//绘画游戏图案
{
    QPainter painter(this);
    painter.drawPixmap(0,0,1900,1000,QPixmap(":/image/GIbg.jpg"));
    if(!blsRun)
    {initplane();}//第一次执行
    painter.setPen(Qt::black);
    painter.setBrush(Qt::gray);
    //    painter.drawPixmap(0,0,1150,590,QPixmap(":images/img/formbackground.jpeg"));
    if(score%2==0)
    {
        painter.drawPixmap(0,800,1900,20,QPixmap(":/image/fengexian.png"));//分割线 800
        painter.drawPixmap(840,750,170,230,QPixmap(":/image/enemy3_n1.png"));//我方武器
        painter.drawPixmap(1700,860,110,110,QPixmap(":/image/xiaoren1.png"));//小人
    }
    else
    {
        painter.drawPixmap(0,800,1900,20,QPixmap(":/image/fengexian.png"));//分割线 800
        painter.drawPixmap(840,750,170,230,QPixmap(":/image/enemy3_n2.png"));//我方武器
        painter.drawPixmap(1660,840,170,150,QPixmap(":/image/xiaoren2.png"));//小人
    }
    for(auto &i:planes)//遍历容器元素
    {
        if(i.tag==0)
        {
            QRect planPicture(i.x,i.y+45,140,110);//单词在飞机前显示
            //            qDebug()<<"测试点二";
            //painter.drawRect(planPicture);
            QFont font("Times New Roman",13,50);
            painter.drawPixmap(i.x,i.y,69,99,QPixmap(":/image/enemy2.png"));
            painter.setPen(Qt::green);
            painter.setFont(font);
            painter.drawText(planPicture,QString(i.word),Qt::AlignHCenter|Qt::AlignVCenter);
        }
        //敌机被击中的情况
        else if(i.tag==1)
        {
            if(timebomb1==0)
            {
                painter.drawPixmap(i.x,i.y,69,99,QPixmap(":/image/enemy2_down3.png"));
                timebomb1++;
            }
            else if(timebomb1>0)
            {
                planes.erase(&i,&i+1);
                timebomb1=0;
            }
        }
        //敌机逃脱的情况
        else
        {
//            if(timebomb1==0)
//            {
                painter.drawPixmap(i.x,i.y+20,69,99,QPixmap(":/image/enemy2_down4.png"));
//                timebomb1++;
//            }
//            else if(timebomb1>0)
//            {
//                planes.erase(&i,&i+1);
//                timebomb1=0;
//            }
        }
    }

    if(blsOver)
    {
        ui->gameover->show();
        ui->pushButton->show();
    }

}

void GameUI::initplane(int options)//设置第一架飞机图案
{
    static int frontNumber=25;
    srand(unsigned(time(0)*frontNumber));
    frontNumber=rand();
    int xdirection=rand()%2;
    int x;
    int y=0;
    x=qrand()%13;
    blsRun=true;//是否第一次初始化
    //设定计时器,450ms 定时器1分钟
    if(options==0)
    {
        timeP=new QTime();
        timeP->start();
        timer=new QTimer(this);
        timer->start(450);
        connect(timer,SIGNAL(timeout()),SLOT(planeupdate()));
    }
    if(blsOver)//停止计时器
    {
        timer->stop();
    }
    QString temp;
    temp=words[planeIndex];//设计单词
    Plane newPlane;
    newPlane.x=x*120;
    newPlane.y=0;
    newPlane.word=temp;
    newPlane.xdirection=xdirection;
    planes.push_back(newPlane);
    planeIndex++;
}


void GameUI::planeupdate()
{
    for(int j=0;j<planes.size();j++)
    {

        Plane &i=planes[j];
        if(i.y+40<750)
        {
            if(i.xdirection==0)//向左移动
            {
                i.x=(i.x-40>=0?i.x-20:0);
                i.y=(i.y+60<=770?i.y+20:730);
                if(i.y==710)
                {
                    if(i.tag!=2)
                    {
                        wrongCount++;
                        wrongWords[wrongCount]=i.word;
                    }
                    i.tag=2;
                }
                if(i.x==0)
                    i.xdirection=1;
            }
            else if(i.xdirection==1)//向右移动
            {
                i.x=(i.x+120<=1900?i.x+20:1820);
                i.y=(i.y+60<=770?i.y+20:730);
                if(i.y==710)
                {
                    if(i.tag!=2)
                    {
                        wrongCount++;
                        wrongWords[wrongCount]=i.word;
                    }
                    i.tag=2;
                }
                if(i.x==1820)
                    i.xdirection=0;
            }
        }
        else
        {
            if(i.tag!=2)
            {
                wrongCount++;
                wrongWords[wrongCount]=i.word;
            }
            i.tag=2;
        }
//        qDebug()<<timeP->elapsed();
//        游戏结束的判断条件：时间到了或者单词失误数达到最大值
        if((timeP->elapsed()>=gameTime)||wrongCount>=Max_wrong)//一分钟
            blsOver=true;
    }

    timeRecord++;
    if(distroynumber>=3)
    {
        if(newplane<3)
        {
            distroynumber=0;
            newplane+=4;
        }
        if(newplane>=3&&newplane<9)
        {
            distroynumber=0;
            newplane+=planeCount_time;
        }
    }

    if(timeRecord>=newplaneTime-newplane)//要出新飞机了
    {
        timeRecord=0;
        initplane(1);
    }
    update();//更新，重新调用paintEvent()
}


void GameUI::keyPressEvent(QKeyEvent *event)
{
    QKeyEvent *key=(QKeyEvent *)event;
    QVector<Plane>::iterator it;
    if(key->key() != Qt::Key_Return)
    {
        inputWord+=key->key();
        ui->UINput->setText(inputWord);
    }
    else
    {

        for(it=planes.begin();it!=planes.end();it++)
        {
            //            注意compare的返回值；比较不区分大小写
            if(inputWord.compare(it->word, Qt::CaseInsensitive)==0)
            {
                it->tag=1;
                update();
                score++;//增加分数
                distroynumber++;//已经摧毁飞机数
                ui->lcdNumber->display(score);//显示分数
                break;
            }
        }
        inputWord="";
        ui->UINput->setText(inputWord);
    }
}

void GameUI::Sleep(int msec)
{
    qint64 dieTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
    while( QDateTime::currentDateTime().toMSecsSinceEpoch()-dieTime < msec )
    {
        QCoreApplication::processEvents(QEventLoop::AllEvents,100);
        QThread::msleep(1);
    }

}
